# encoding:utf8

from __future__ import unicode_literals

from django.db import models

# Create your models here.
import datetime
import decimal
from django.db import models
from django.utils import timezone
from django.db.models.signals import post_save
from django.dispatch import receiver

DEPARTMENT = (('行政部', '行政部'), ('市场部', '市场部'), ('技术部', '技术部'))


class Staff(models.Model):
    staff_name = models.CharField(max_length=20, verbose_name='姓名')
    department = models.CharField(max_length=20, choices=DEPARTMENT, verbose_name='部门')
    bank_id = models.CharField(max_length=20, verbose_name='银行卡号')
    salary_end = models.DecimalField(max_digits=7, decimal_places=2, default=0, help_text='计算所得', verbose_name='银行发放工资')
    salary_base = models.DecimalField(max_digits=7, decimal_places=2, default=0, verbose_name='基本工资')
    salary_meal = models.DecimalField(max_digits=7, decimal_places=2, default=0, verbose_name='餐补')
    salary_traffic = models.DecimalField(max_digits=7, decimal_places=2, default=0, verbose_name='交补')
    retire_insurance = models.DecimalField(max_digits=7, decimal_places=2, default=0, verbose_name='养老险')
    unemploy_insurance = models.DecimalField(max_digits=7, decimal_places=2, default=0, verbose_name='失业险')
    medical_insurance = models.DecimalField(max_digits=7, decimal_places=2, default=0, verbose_name='医疗险')
    housing_fund = models.DecimalField(max_digits=7, decimal_places=2, default=0, verbose_name='公积金')
    salary_takeoff = models.DecimalField(max_digits=7, decimal_places=2, default=0, help_text='计算所得', verbose_name='请假扣除')
    tax = models.DecimalField(max_digits=7, decimal_places=2, default=0, help_text='计算所得', verbose_name='税收')

    def save(self, *args, **kwargs):
        """从Absent导入上月请假天数"""
        """TODO: 计算方式还需完善，如果是隔2个月发工资如何办？ year/month应该取得是salary_month，而不是salary_date"""
        year = datetime.date.today().year
        month = datetime.date.today().month

        if month != 1:
            absents = Absent.objects.filter(staff__id=self.pk, absent_date__year=year, absent_date__month=month - 1)
        else:
            absents = Absent.objects.filter(staff__id=self.pk, absent_date__year=year - 1, absent_date__month=12)
        num = 0
        for absent in absents:
            num += absent.absent_num
        self.salary_takeoff = num * self.salary_base / 22

        """在此加入工资计算
        银行发放工资 = 基本工资 + 餐补 + 交补 - 养老险 - 失业险 - 医疗险 - 公积金 - 请假扣除 - 税收"""

        money = self.salary_base + self.salary_meal + self.salary_traffic - self.retire_insurance - \
                self.unemploy_insurance - self.medical_insurance - self.housing_fund - \
                self.salary_takeoff - 3500

        if money < 0:
            self.tax = 0
        elif money < 1500:
            self.tax = money * decimal.Decimal(0.03)
        elif money < 4500:
            self.tax = money * decimal.Decimal(0.1) - 105
        elif money < 9000:
            self.tax = money * decimal.Decimal(0.2) - 555
        elif money < 35000:
            self.tax = money * decimal.Decimal(0.25) - 1005
        elif money < 55000:
            self.tax = money * decimal.Decimal(0.3) - 2755
        elif money < 80000:
            self.tax = money * decimal.Decimal(0.35) - 5505
        else:
            self.tax = money * decimal.Decimal(0.45) - 13505

        self.salary_end = money + 3500 - self.tax

        super(Staff, self).save(*args, **kwargs)

    def __unicode__(self):
        return str(self.staff_name)

    class Meta:
        verbose_name_plural = u'员工信息'


class Salary(models.Model):
    staff = models.ForeignKey(Staff, verbose_name='姓名')
    salary_end = models.DecimalField(max_digits=7, decimal_places=2, default=0, help_text='计算所得', verbose_name='银行发放工资')
    salary_base = models.DecimalField(max_digits=7, decimal_places=2, default=0, verbose_name='基本工资')
    salary_date = models.DateField(blank=True, null=True, verbose_name='发放工资日期')
    salary_month = models.CharField(max_length=20, verbose_name='工资月份')
    salary_meal = models.DecimalField(max_digits=7, decimal_places=2, default=0, verbose_name='餐补')
    salary_traffic = models.DecimalField(max_digits=7, decimal_places=2, default=0, verbose_name='交补')
    retire_insurance = models.DecimalField(max_digits=7, decimal_places=2, default=0, verbose_name='养老险')
    unemploy_insurance = models.DecimalField(max_digits=7, decimal_places=2, default=0, verbose_name='失业险')
    medical_insurance = models.DecimalField(max_digits=7, decimal_places=2, default=0, verbose_name='医疗险')
    housing_fund = models.DecimalField(max_digits=7, decimal_places=2, default=0, verbose_name='公积金')
    salary_takeoff = models.DecimalField(max_digits=7, decimal_places=2, default=0, help_text='计算所得', verbose_name='请假扣除')
    tax = models.DecimalField(max_digits=7, decimal_places=2, default=0, help_text='计算所得', verbose_name='税收')

    def __unicode__(self):
        return str(self.staff)

    class Meta:
        verbose_name_plural = u'工资发放记录'


class Absent(models.Model):
    staff = models.ForeignKey(Staff, verbose_name='姓名')
    absent_date = models.DateField(blank=True, null=True, verbose_name='日期')
    absent_num = models.DecimalField(max_digits=7, decimal_places=2, default=0, verbose_name='请假天数')

    def __unicode__(self):
        return str(self.staff)

    class Meta:
        verbose_name_plural = '请假信息'


@receiver(post_save, sender=Absent)
def update_salary(sender, instance, **kwargs):
    objects = Staff.objects.filter(staff_name=instance.staff)
    for object in objects:
        object.save()

    # """暂时假定Salary.salary_date的月份和请假的月份一样，Salary.salary_date的月份只会比Salary,salary_month多1个月"""
    # year = instance.absent_date.year
    # month = instance.absent_date.month
    # if month != 12:
    #     objects = Salary.objects.filter(staff=instance.staff, salary_date__year=year, salary_date__month=month+1)
    # else:
    #     objects = Salary.objects.filter(staff=instance.staff, salary_date__year=year + 1, salary_date__month=1)
    # for object in objects:
    #     object.save()